<template>
  <div class="receipt-detail">
    <div class="page-header">
      <div class="title-wrapper">
        <h2 class="page-title">收货单详情</h2>
        <span v-if="receipt.receiptNumber" class="receipt-number">
          {{ receipt.receiptNumber }}
        </span>
      </div>
      <div class="actions">
        <el-button @click="goBack">
          <el-icon>
            <ArrowLeft/>
          </el-icon>
          返回
        </el-button>
        <el-button v-if="receipt.status === '待验收'" type="primary" @click="handleEdit">
          <el-icon>
            <Edit/>
          </el-icon>
          编辑
        </el-button>
        <el-button v-if="receipt.status === '待验收'" type="primary" @click="handleAccept">
          <el-icon>
            <Check/>
          </el-icon>
          验收
        </el-button>
        <el-button v-if="receipt.status === '待验收'" type="danger" @click="handleDelete">
          <el-icon>
            <Delete/>
          </el-icon>
          删除
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon>
            <Download/>
          </el-icon>
          导出
        </el-button>
      </div>
    </div>

    <el-card v-loading="loading" class="detail-card" shadow="hover">
      <el-empty v-if="!receipt.id && !loading" description="未找到收货单信息"></el-empty>

      <template v-else>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="收货单号">{{ receipt.receiptNumber }}</el-descriptions-item>
          <el-descriptions-item label="关联订单">
            <el-button link type="primary" @click="viewOrder(receipt.orderId)">
              {{ receipt.orderNumber || '未关联订单' }}
            </el-button>
          </el-descriptions-item>
          <el-descriptions-item label="供应商">{{ receipt.supplierName }}</el-descriptions-item>
          <el-descriptions-item label="收货日期">{{ receipt.receiptDate || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="收货单状态">
            <el-tag :type="receipt.status === '已验收' ? 'success' : 'warning'">
              {{ receipt.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="收货人">{{ receipt.consignee || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ receipt.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ receipt.updateTime || '未更新' }}</el-descriptions-item>
          <el-descriptions-item label="总金额">
            <span class="amount">{{ formatCurrency(receipt.totalAmount) }}</span>
          </el-descriptions-item>
          <!--          <el-descriptions-item :span="3" label="备注">-->
          <!--            {{ receipt.remark || '无备注信息' }}-->
          <!--          </el-descriptions-item>-->
        </el-descriptions>

        <div class="section-title">收货明细</div>
        <el-table :data="receipt.items || []" border style="width: 100%">
          <el-table-column label="序号" type="index" width="60"></el-table-column>
          <el-table-column label="物品名称" min-width="180" prop="itemName"/>
          <el-table-column label="规格" min-width="120" prop="specification"/>
          <el-table-column label="单位" prop="unit" width="80"/>
          <el-table-column label="数量" prop="quantity" width="100">
            <template #default="{ row }">
              {{ row.quantity }}
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="unitPrice" width="120">
            <template #default="{ row }">
              {{ formatCurrency(row.unitPrice) }}
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="total" width="120">
            <template #default="{ row }">
              {{ formatCurrency(row.total) }}
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>

    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="deleteDialogVisible"
        destroy-on-close
        title="确认删除"
        width="30%"
    >
      <div class="delete-warning">
        <el-icon class="warning-icon">
          <Warning/>
        </el-icon>
        <p>确定要删除收货单 "{{ receipt.receiptNumber }}" 吗？此操作不可撤销。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button
              :loading="deleteLoading"
              type="danger"
              @click="confirmDelete"
          >确认删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 验收确认对话框 -->
    <el-dialog
        v-model="acceptDialogVisible"
        destroy-on-close
        title="确认验收"
        width="30%"
    >
      <div class="accept-confirm">
        <p>确定要验收收货单 "{{ receipt.receiptNumber }}" 吗？</p>
        <p class="warning-text">验收后收货单状态将变更为"已验收"，不可再进行编辑。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="acceptDialogVisible = false">取消</el-button>
          <el-button
              :loading="acceptLoading"
              type="primary"
              @click="confirmAccept"
          >确认验收</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import {ArrowLeft, Check, Delete, Download, Edit, Warning} from '@element-plus/icons-vue';
import type {Receipt} from '@/api/receipt';
import {acceptReceipt, deleteReceipt, exportReceipt, getReceiptDetail} from '@/api/receipt';

const route = useRoute();
const router = useRouter();
const receiptId = ref(route.params.id as string);

// 状态
const loading = ref(false);
const deleteDialogVisible = ref(false);
const deleteLoading = ref(false);
const acceptDialogVisible = ref(false);
const acceptLoading = ref(false);
const receipt = ref<Receipt & Record<string, any>>({
  receiptNumber: '',
  orderId: 0,
  supplierName: '',
  status: '',
  totalAmount: 0,
  items: []
});

// 获取收货单详情
const fetchReceiptDetail = async () => {
  if (!receiptId.value) {
    ElMessage.error('收货单ID无效');
    return;
  }

  loading.value = true;
  try {
    const res = await getReceiptDetail(receiptId.value);
    if (res.code === 200 && res.data) {
      receipt.value = res.data;
    } else {
      ElMessage.warning('未找到收货单信息');
    }
  } catch (error) {
    console.error('获取收货单详情失败:', error);
    ElMessage.error('获取收货单详情失败');
  } finally {
    loading.value = false;
  }
};

// 页面加载
onMounted(() => {
  fetchReceiptDetail();
});

// 返回列表页
const goBack = () => {
  router.push('/dashboard/receipt-list');
};

// 编辑收货单
const handleEdit = () => {
  router.push(`/dashboard/receipt-edit/${receiptId.value}`);
};

// 查看关联订单
const viewOrder = (orderId: number | string | undefined) => {
  if (orderId) {
    router.push(`/dashboard/order-detail/${String(orderId)}`);
  } else {
    ElMessage.warning('未关联订单');
  }
};

// 删除收货单
const handleDelete = () => {
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  deleteLoading.value = true;
  try {
    const res = await deleteReceipt(receiptId.value);
    if (res.code === 200) {
      ElMessage.success('收货单删除成功');
      deleteDialogVisible.value = false;
      router.push('/dashboard/receipt-list');
    } else {
      ElMessage.error(res.message || '删除失败');
    }
  } catch (error) {
    console.error('删除收货单失败:', error);
    ElMessage.error('删除收货单失败');
  } finally {
    deleteLoading.value = false;
  }
};

// 验收收货单
const handleAccept = () => {
  acceptDialogVisible.value = true;
};

// 确认验收
const confirmAccept = async () => {
  acceptLoading.value = true;
  try {
    const res = await acceptReceipt(receiptId.value, '已验收');
    if (res.code === 200) {
      ElMessage.success('收货单验收成功');
      acceptDialogVisible.value = false;
      // 刷新数据
      fetchReceiptDetail();
    } else {
      ElMessage.error(res.message || '验收失败');
    }
  } catch (error) {
    console.error('验收收货单失败:', error);
    ElMessage.error('验收收货单失败');
  } finally {
    acceptLoading.value = false;
  }
};

// 导出收货单
const handleExport = async () => {
  try {
    const res = await exportReceipt({
      receiptNumber: receipt.value.receiptNumber
    });

    // 处理blob响应
    if (res.data instanceof Blob) {
      // 创建下载链接
      const blob = res.data;
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `收货单_${receipt.value.receiptNumber}.xlsx`;
      link.click();
      URL.revokeObjectURL(link.href);
      ElMessage.success('收货单导出成功');
    } else {
      // 如果不是blob，可能是错误响应
      ElMessage.warning('导出失败，请稍后再试');
    }
  } catch (error) {
    console.error('导出收货单失败:', error);
    ElMessage.error('导出收货单失败');
  }
};

// 格式化日期
// const formatDate = (date?: string | Date) => {
//   if (!date) return '';
//   if (typeof date === 'string') {
//     // 如果是ISO字符串格式，截取年月日部分
//     if (date.includes('T')) {
//       return date.split('T')[0];
//     }
//     return date;
//   }
//   const d = new Date(date);
//   return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
// };

// 格式化货币
const formatCurrency = (amount?: number) => {
  if (amount === undefined || amount === null) return '¥0.00';
  return `¥${Number(amount).toFixed(2)}`;
};

// 获取状态类型
// const getStatusType = (status?: string) => {
//   const typeMap: Record<string, 'success' | 'warning' | 'info' | 'danger'> = {
//     '待验收': 'warning',
//     '已验收': 'success',
//     '已取消': 'info'
//   };
//   return typeMap[status || ''] || 'info';
// };
</script>

<style scoped>
.receipt-detail {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-wrapper {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.receipt-number {
  font-size: 16px;
  color: #909399;
}

.actions {
  display: flex;
  gap: 10px;
}

.detail-card {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin: 20px 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.amount {
  font-weight: bold;
  color: #f56c6c;
  font-size: 16px;
}

.delete-warning {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.warning-icon {
  color: #f56c6c;
  font-size: 24px;
}

.accept-confirm {
  line-height: 1.5;
}

.warning-text {
  color: #e6a23c;
  font-size: 14px;
  margin-top: 10px;
}
</style> 